import { clone } from "@pureadmin/utils";
import { ref } from "vue";

const isDisabled = ref(false);
const timer = ref(null);
const showTime = ref(0);

export const countDown = () => {
  const start = async (time = 60) => {
    const initTime = clone(time, true);
    clearInterval(timer.value);
    isDisabled.value = true;
    showTime.value = time;
    timer.value = setInterval(() => {
      if (time > 0) {
        time -= 1;
        showTime.value = time;
      } else {
        showTime.value = 0;
        isDisabled.value = false;
        clearInterval(timer.value);
        time = initTime;
      }
    }, 1000);
  };

  const end = () => {
    showTime.value = 0;
    isDisabled.value = false;
    clearInterval(timer.value);
  };

  return {
    isDisabled,
    timer,
    showTime,
    start,
    end
  };
};
